package org.cvcsc.weproject.filter;

import io.jsonwebtoken.Claims;
import org.cvcsc.weproject.util.JwtUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtUtil jwtUtil;

    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = extractToken(request);
        if (token != null && jwtUtil.parseToken(token) != null) {
            // 解析Token
            Claims claims = jwtUtil.parseToken(token);

            // 获取用户ID和角色
            Long userId = Long.valueOf(claims.getSubject());
            boolean isAdmin= claims.get("isAdmin", Boolean.class);
            //TODO


            // 创建认证对象
            //   List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(role));
            //   UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userId, null,
            //          authorities);

            // 设置认证信息到SecurityContext
            //  SecurityContextHolder.getContext().setAuthentication(authentication);


        }
        filterChain.doFilter(request, response);
    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}